package cn.java71.servlet;

import cn.java71.entity.Subject;
import cn.java71.service.StudentService;
import cn.java71.service.SubjectService;
import cn.java71.servlet.ctrl.AdminController;
import cn.java71.servlet.ctrl.CourseController;
import cn.java71.servlet.ctrl.UserController;
import cn.java71.util.StrUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet(name = "MainServlet", value = "*.do")
public class MainServlet extends HttpServlet {

    private UserController u=new UserController();
    private CourseController c=new CourseController();
    private AdminController admin=new AdminController();
    //请求地址分成两部分
    //表示控制器，第二部分是请求地址，中间有-隔开，
    //用反射访问
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得请求地址：
        String path = request.getServletPath();
        //去掉开头的/ 和结尾的  .do
        path = path.substring(1, path.length() - 3);
        if (path.equals("service") || path.equals("doGet") || path.equals("doPost")) {
            response.sendError(500, "禁止访问此地址！");
            return;
        }
        //path就是方法名，参数是固定的request和response
        try {
            String []ar=path.split("-");
            if(ar.length==1){
                Method method = this.getClass().getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this, request, response);//调用
                return;
            }
            String controller=ar[0];
            String method=ar[1];
            Field field = this.getClass().getDeclaredField(controller);
            //field.setAccessible(true);//取消私有的限制
            Object obj=field.get(this);//拿到了属性
            Method m=obj.getClass().getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            m.invoke(obj,request,response);

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(501, "出错了，信息是：" + e);
        }
    }


//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //获得请求地址：
//        String path = request.getServletPath();
//        //去掉开头的/ 和结尾的  .do
//        path = path.substring(1, path.length() - 3);
//        if (path.equals("service") || path.equals("doGet") || path.equals("doPost")) {
//            response.sendError(500, "禁止访问此地址！");
//            return;
//        }
//        //path就是方法名，参数是固定的request和response
//        try {
//            Method method = this.getClass().getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
//            method.invoke(this, request, response);//调用
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.sendError(501, "出错了，信息是：" + e);
//        }
//    }

    StudentService studentService = new StudentService();

    SubjectService subjectService = new SubjectService();

    public void subjectSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int pageNo = StrUtil.toInt(request.getParameter("p"), 1);
        int pageSize = 10;
        List<Subject> list = subjectService.paging(pageNo, pageSize);
        //封装成json格式
//        StringBuilder sb = new StringBuilder();
//        sb.append("[");
//        for (int i = 0; i < list.size(); i++) {
//            Subject s = list.get(i);
//            sb.append("{");
//            sb.append("\"id\":" + s.getId());
//            sb.append(",\"subjectname\":\"" + s.getSubjectname() + "\"");
//            sb.append(",\"classhour\":" + s.getClasshour());
//            sb.append(",\"gradeid\":" + s.getGradeid());
//            sb.append("}");
//            if (i < list.size() - 1)
//                sb.append(",");
//        }
//        sb.append("]");
        String sb= JSON.toJSONString(list);
        System.out.println(sb);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(sb);
    }

    public void checkPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("telephone");
        boolean f = studentService.checkTelephone(phone);
        //out给出结果
        try {
            Thread.sleep(4500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        out.print(f);////?????? !!!!
        out.flush();
    }

    //    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //获得请求地址：
//        String path = request.getServletPath();
//        //去掉开头的/ 和结尾的  .do
//        path = path.substring(1, path.length() - 3);
//
//        if (path.equals("login")) {
//            login(request, response);
//        } else if (path.equals("update")) {
//            update(request, response);
//        } else if (path.equals("del")) {
//            del(request, response);
//        } else if (path.equals("search")) {
//
//        } else {
//
//        }
//
//
//    }
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("这是修改");
    }

    private void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("这是删除");
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        if ("admin".equals(name) && "12345".equals(pass)) {
//            request.getRequestDispatcher("/welcome.jsp").forward(request,response);
            response.sendRedirect("welcome.jsp");
        } else {
            request.setAttribute("msg", "错误的用户名或者密码！");
            request.getRequestDispatcher("/test1.jsp").forward(request, response);
        }
    }

//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //获得请求地址：
//        String path=request.getServletPath();
//        //去掉开头的/ 和结尾的  .do
//        path=path.substring(1,path.length()-3);
//
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
//        out.write("<html>");
//        out.write("<body>");
//        out.write("<h1>contextpath="+request.getContextPath()+"</h1>");
//        out.write("<h1>请求路径:"+request.getServletPath()+"</h1>");
//        out.write("<h1>端口："+request.getServerPort()+"</h1>");
//        out.write("<h1>URL:"+request.getRequestURL()+"</h1>");
//        out.write("<h1>URI:"+request.getRequestURI()+"</h1>");
//        out.write("<h1>query string:"+request.getQueryString()+"</h1>");
//        if(path.equals("login")){
//            out.write("<h2 style='color:red;'>这是登录</h2>");
//            String name=request.getParameter("user");
//            String pass=request.getParameter("pass");
//            //.....
//            //request.getRequestDispatcher("//xxx.jsp").forward();
//        }else if(path.equals("update")){
//            out.write("<h2 style='color:red;'>这是修改</h2>");
//        }else if(path.equals("del")){
//            out.write("<h2 style='color:red;'>这是删除</h2>");
//        }else if(path.equals("search")){
//            out.write("<h2 style='color:red;'>这是查询</h2>");
//        }else{
//            out.write("<h2 style='color:red;'>这是未知操作</h2>");
//        }
//        out.write("</body>");
//
//
//        out.write("</html>");
//
//    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
//        String op=request.getParameter("operate");
//        if ("add".equals(op)) {
//
//        }else if("delete".equals(op)){
//
//        }
    }
}
